//
//  MensaParser.m
//  MensaViewer
//
//  Created by Markus Dauberschmidt on 06.04.11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MensaParser.h"

@implementation MensaParser

@synthesize menu;

-(id) init 
{
    self = [super init];
    menu = [[NSMutableArray alloc]init];
    [menu retain];
    return self;
}

-(void) dealloc 
{
    [menu release];
    [super dealloc];
}
/*
 - (void)reachabilityChanged:(NSNotification *)note {
 [self updateStatus];
 }*/

-(void) parseIt:(NSData *) data {
    parser = [[NSXMLParser alloc] initWithData:data];
    
    [parser setDelegate:self];
    [parser parse];
    [parser release];

}
-(void) parseLocalData
{
    // create the connection with the request
    // and start loading the data
    
   // NSURL *xmlurl = [[NSURL alloc] initFileURLWithPath:@"cache.xml"];
    
    // Query the SystemConfiguration framework for the state of the device's network connections.
    /*
     self.internetConnectionStatus    = [[Reachability sharedReachability] internetConnectionStatus];
     if (self.internetConnectionStatus == NotReachable) {
     //show an alert to let the user know that they can't connect...
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Status" message:@"Sorry, our network guro determined that the network is not available. Please try again later." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
     [alert show];
     }  else {
     // If the network is reachable, make sure the login button is enabled.
     ;
     }
     */
    //parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlurl];
    NSData *data = [[NSData alloc] initWithContentsOfFile:@"cache.xml"];
    [self parseIt:data];
        
}
-(void) parseXML:(NSString *)url {
    //[self parseLocalData];
    
    
    // DEBUG
    
    
    
    // Check whether we are online, then use the live version and store locally
    //NSString *path=[NSTemporaryDirectory() stringByAppendingString:@"cache.xml"];
    
    
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    //NSURLConnection *theConnection=[[NSURLConnection alloc] init];
    NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
    NSLog(@"Succeeded! Received %d bytes of data",[data length]);
    if([data writeToFile:@"cache.xml" atomically:YES]) {
        NSLog(@"Ois supa!");
    }
    // release the connection, and the data object
    //[connection release];
    //[self parseLocalData];
    [self parseIt:data];
    //    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    /* if (theConnection) {
     // Create the NSMutableData to hold the received data.
     // receivedData is an instance variable declared elsewhere.
     receivedData = [[NSMutableData data] retain];
     } else {
     NSLog(@"Failed!");
     }*/
    
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    // NSLog(@"%@",elementName);
    // NSArray *arr = [attributeDict allKeys];
    
    if ([elementName isEqualToString:@"Tagesplan"]) {
        if (myDailyMenu!=nil) {
            [menu addObject:myDailyMenu];
            [myDailyMenu release];
        } 
        
        NSString *tag = (NSString*) [attributeDict objectForKey:@"tag"];
        myDailyMenu = [[DailyMenu alloc] initWithDateString:tag];
        [myDailyMenu retain];
        
    }
    if ([elementName isEqualToString:@"Gericht"]) {
        myMeal = [[Meal alloc] initWithName: [attributeDict objectForKey:@"name"] andPrice:[attributeDict objectForKey:@"preis"]];
        [myDailyMenu.meals addObject:myMeal];
        [myMeal release];
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    [receivedData writeToFile:@"cache.xml" atomically:YES];
    // release the connection, and the data object
    [connection release];
    [receivedData release];
    [self parseLocalData];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.
    
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    
    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
    
    // Store in filesystem
    
}
@end
